package com.jwt.Handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwt.pojo.ResponseResult;
import com.jwt.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class JwtLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Resource
	ObjectMapper objectMapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
		String token= JwtUtils.generateToken(authentication);
		response.setContentType("application/json;charset=utf-8");
		ResponseResult<?> result=new ResponseResult<>();
		result.setCode(1);
		result.setFlag(true);
		result.setAuthorization(token);
		String s = objectMapper.writeValueAsString(result);
		response.getWriter().write(s);
	}
}
